<?php
/**
 * Daemon.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/11/5- 10:37 上午
 */
namespace console\components\daemons\copy;
use Yii;
class Daemon
{
    /**
     * 启动守护进程
     * @param bool $daemon
     * @return bool
     */
    public static function start(bool $daemon = false): bool
    {

        $processIdPath = Yii::getAlias(Yii::$app->params['daemon']['copy']['masterPidFilePath']);

        if (is_file($processIdPath))
        {
            /**
             * 进程id存在，则先杀尝试杀掉log中记录的进程id
             */
            $processArr = file($processIdPath);
            foreach($processArr as $processId)
            {
                $processId = trim($processId);
                ($processId > 0) && @posix_kill($processId, SIGTERM);
            }
        }


        $masterProcessor = new Worker($daemon);
        $masterProcessor->run();

        return true;
    }

    /**
     * 关闭守护进程
     */
    public static function stop(): void
    {
        $processIdPath = Yii::getAlias(Yii::$app->params['daemon']['copy']['masterPidFilePath']);

        if (is_file($processIdPath))
        {
            $processArr = file($processIdPath);

            foreach($processArr as $processId)
            {
                $processId = trim($processId);
                ($processId > 0) && @posix_kill($processId, SIGTERM);
            }

            @unlink($processIdPath);
        }
    }
}
